from openpyxl import load_workbook
from tqdm import tqdm


def read_xlsx(filename, sheets=None, **kwargs):
    result = dict()
    wb = load_workbook(filename, **kwargs)
    if not sheets:
        sheets = wb.sheetnames
    for sheet in sheets:
        ws = wb[sheet]
        rows_data = ws.rows
        header = [cell.value for cell in next(rows_data)]
        if header[-1] is None:
            header.pop()
        elem_len = len(header)
        print(f"sheet {sheet}, header {elem_len}\n{header}")
        print(f"sheet {sheet}, max_row {ws.max_row}, max_column {ws.max_column}")
        rows = list()
        for row_num, row_data in tqdm(enumerate(rows_data), total=ws.max_row-1):
            row_num += 2
            row = [cell.value for cell in row_data]
            if len(row) > elem_len and row[-1] is None:
                row.pop()
            if len(row) != elem_len:
                raise Exception(f"header and data don't match, line {row_num}, header: {header}, row：{row}")
            rows.append(row)
        result[sheet] = dict(header=header, rows=rows)
    return result


def is_valid_row(row: list):
    return not all((v is None or v == '' for v in row))


def unify_row(row: list, unify_ignore: list = None):
    unify_ignore = [] if not unify_ignore else unify_ignore
    for i in range(len(row)):
        v = row[i]
        if v is None:
            v = ''
        if not isinstance(v, str):
            v = str(v)
        if i not in unify_ignore:
            v = v.lower()
        row[i] = v.strip()
    return row


def is_empty_value(value):
    if value is None:
        return True
    if isinstance(value, str):
        if value == '' or value == "-":
            return True
    return False
